package com.pickgliss.render2d.vo
{
	import com.pickgliss.render2d.events.LayerEvent;
	
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
		
	[Event(name="itemAdd", type="com.pickgliss.render2d.events.LayerEvent")]
	[Event(name="itemRemove", type="com.pickgliss.render2d.events.LayerEvent")]
	public class LayerInfo extends EventDispatcher implements IReadWriteAble
	{
		public static const GRAPHIC:String = "graphic";
		public static const COPY:String = "copy";
		public var layerType:String = "";
		public var renderType:String = "";
		public var mapItems:Vector.<MapItem> = new Vector.<MapItem>();
		public var visible:Boolean=true;
		public var name:String = "";
		public var layerIndex:int = 0;
		public function toBytearray():ByteArray
		{
			var result:ByteArray = new ByteArray();
			result.writeUTF(name);
			result.writeInt(layerIndex);
			result.writeUTF(layerType);
			result.writeUTF(renderType);
			result.writeBoolean(visible);
			result.writeInt(mapItems.length);
			for(var i:int = 0;i<mapItems.length;i++)
			{
				var item:ByteArray = mapItems[i].toBytearray();
				result.writeBytes(item,0,item.length);
			}
			
			return result;
		}
		
		
		public function addMapItem(item:MapItem):void
		{
			mapItems.push(item);
			dispatchEvent(new LayerEvent(LayerEvent.ITEM_ADD,item));
		}
		
		public function removeMapItem(item:MapItem):void
		{
			mapItems.splice(mapItems.indexOf(item),1);
			dispatchEvent(new LayerEvent(LayerEvent.ITEM_REMOVE,item));
		}
		
		public function readFromBytearray(b:ByteArray):void
		{
			name = b.readUTF();
			layerIndex = b.readInt();
			layerType = b.readUTF();
			renderType = b.readUTF();
			visible = b.readBoolean();
			var count:int = b.readInt();
			for(var i:int = 0;i<count;i++)
			{
				var item:MapItem = new MapItem();
				item.readFromBytearray(b);
				addMapItem(item);
			}
		}
	}
}